<!--
 * @Date: 2024-01-12 17:19:44
 * @LastEditors: truman
 * @LastEditTime: 2024-03-10 16:13:34
 * @FilePath: \newbee-mall-vue3-app\src\views\pwd.vue
-->
<template>
  <div class="seting-box">
    <s-header :name="state.isHave ? '绑定用户' : '注册账号'"></s-header>
    <template v-if="state.isHave">
      <van-form @submit="onSubmit">
        <div class="input-item">
          <van-field
            v-model="state.form.tel"
            label="手机号"
            :rules="[{ required: true, message: '请填写手机号' }]"
          />
        </div>
        <van-button
          round
          class="save-btn"
          color="#1baeae"
          type="primary"
          native-type="submit"
          block
          >提交</van-button
        >
      </van-form>
    </template>
    <template v-else>
      <div class="login-body register">
        <van-form @submit="onSubmit2">
          <van-field
            v-model="state.username1"
            name="username1"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="state.nickname"
            name="nickname"
            label="姓名"
            placeholder="姓名"
          />
          <van-field
            v-model="state.password1"
            type="password"
            name="password1"
            label="密码"
            placeholder="密码"
            :rules="[
              { required: true, message: '请填写密码' },
              {
                pattern:
                  /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/,
                message:
                  '密码必须包含大小写字母、数字、特殊字符中至少3种  并且位数不小于8',
                trigger: 'onBlur',
              },
            ]"
          />
          <van-field
            v-model="state.confirm_password"
            type="password"
            name="confirm_password"
            label="确认密码"
            placeholder="确认密码"
            :rules="pwdRule(state.confirm_password)"
          />
          <van-field
            v-model="state.we_chat"
            name="we_chat"
            label="微信号"
            placeholder="微信号"
          />
          <van-field
            v-model="state.tel"
            name="tel"
            label="手机号"
            placeholder="手机号"
            :rules="[
              { required: true, message: '请填写手机号' },
              {
                pattern: /^1[3456789]\d{9}$/,
                message: '手机号码格式错误！',
                trigger: 'onChange',
              },
            ]"
          />
          <van-field name="radio" label="用户类型">
            <template #input>
              <van-checkbox-group v-model="state.roletype">
                <!-- <van-radio name="2">个人</van-radio> -->
                <van-checkbox name="3">供应商</van-checkbox>
                <van-checkbox name="6">需求商</van-checkbox>
              </van-checkbox-group>
            </template>
          </van-field>
          <div style="margin: 16px">
            <van-button round block color="#1baeae" native-type="submit"
              >注册</van-button
            >
          </div>
        </van-form>
      </div>
    </template>

    <van-action-sheet
      v-model:show="state.show"
      :actions="actions"
      @select="onSelect"
    />
  </div>
</template>

<script setup>
import { reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "@/stores/index";
import sHeader from "@/components/SimpleHeader.vue";
import { bindUser, register, login } from "@/service/user";
import { setLocal } from "@/common/js/utils";
import { showSuccessToast, showToast } from "vant";
const router = useRouter();
const store = useStore();
const state = reactive({
  form: {
    username: "",
    tel: "",
  },
  show: true,
  isHave: false,
  username: "",
  password: "",
  username1: "",
  password1: "",
  type: "login",
  imgCode: "",
  verify: "",
  we_chat: "",
  qq: "",
  tel: "",
  roletype: [],
  confirm_password: "",
  nickname: "",
});

const actions = [{ name: "已有平台账户" }, { name: "完全没接触过" }];
const onSelect = (item) => {
  state.show = false;
  if (item.name === "已有平台账户") {
    state.isHave = true;
  } else {
    state.isHave = false;
  }
};

onMounted(async () => {});

const isConfirmPassword = (value) => {
  return state.password1 === value;
};

const pwdRule = (obj) => {
  return [
    { required: true, message: "请填写密码" },
    {
      pattern:
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/,
      message:
        "密码必须包含大小写字母、数字、特殊字符中至少3种  并且位数不小于8",
      trigger: "onBlur",
    },
    {
      obj,
      validator: isConfirmPassword,
      message: "两遍密码不相同",
      trigger: "onBlur",
    },
  ];
};

const doLogin = async (res) => {
  try {
    const data = await login({
      username: res.username,
      password: res.password,
    });

    setLocal("access_token", `Bearer ${data.access_token}`);
    setLocal("refresh_token", `Bearer ${data.refresh_token}`);

    showToast({
      message: "登录成功",
      className: "particulars-detail-popup",
    });
    setTimeout(() => {
      router.push({ path: `/home` });
    }, 500);
  } catch (err) {
    console.log(err);
    showToast({
      message: "账号或密码错误！",
      className: "particulars-detail-popup",
    });
  }
};

const bind = async (val) => {
  try {
    const params = {
      openid: store.loginInfo.openid,
      avatar: store.loginInfo.avatar,
    };

    const res = await bindUser(val, params);
    doLogin(res);
    showToast({
      message: res ? "绑定成功" : "绑定失败",
      className: "particulars-detail-popup",
    });
  } catch (error) {
    if (error.id) {
      doLogin(error);
      showToast({
        message: error ? "绑定成功" : "绑定失败",
        className: "particulars-detail-popup",
      });
    } else {
      showToast({
        message: error.response.data.message || "绑定失败",
        className: "particulars-detail-popup",
      });
    }
  }
};

const onSubmit = async () => {
  bind(state.form.tel);
};

const onSubmit2 = async (values) => {
  const finalCheckPwd =
    /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/;

  // 两次密码必须相同
  if (values.password1 !== values.confirm_password) {
    showToast({
      message: "两遍密码必须相同",
      className: "particulars-detail-popup",
    });
    return;
  }

  const checkPwd = finalCheckPwd.test(values.password1);

  if (!checkPwd) {
    showToast({
      message:
        "密码必须包含大小写字母、数字、特殊字符中至少3种  并且位数不小于8",
      className: "particulars-detail-popup",
    });
    return;
  }

  const name = values.nickname === "" ? values.username1 : values.nickname;
  const res = await register({
    username: values.username1,
    password: values.password1,
    we_chat: values.we_chat,
    qq: "待填写",
    tel: values.tel,
    roletype: state.roletype,
    nickname: name,
    confirm_password: values.confirm_password,
    group_ids: state.roletype,
  })
    .then((res) => {
      bind(values.tel)
      showToast({
        message: res.message ? res.message : "注册成功",
        className: "particulars-detail-popup",
      });
    })
    .catch((err) => {
      let e = "";
      for (const key in err.response.data.message) {
        if (Object.hasOwnProperty.call(err.response.data.message, key)) {
          const el = err.response.data.message[key];

          e += el;
        }
      }
      showToast({
        message: e,
        className: "particulars-detail-popup",
      });
    });
};
</script>

<style lang="less" scoped>
.seting-box {
  .save-btn {
    width: 80%;
    margin: 20px auto;
  }
}

.login {
  .link-register {
    font-size: 14px;
    margin-bottom: 20px;
    color: #1989fa;
    display: inline-block;
  }
}
.register {
  .link-login {
    font-size: 14px;
    margin-bottom: 20px;
    color: #1989fa;
    display: inline-block;
  }
}
</style>
